package com.aliang.shopping.controller;


import cn.hutool.core.bean.BeanUtil;
import com.aliang.shopping.common.Result;
import com.aliang.shopping.common.ResultCodeEnum;
import com.aliang.shopping.config.OssConfig;
import com.aliang.shopping.contact.ResultMsgContact;
import com.aliang.shopping.exception.DataException;
import com.aliang.shopping.log.annotation.OperateLog;
import com.aliang.shopping.log.enums.OperateType;
import com.aliang.shopping.model.converter.CommentConverter;
import com.aliang.shopping.model.dto.comment.CommentInsertDTO;
import com.aliang.shopping.model.po.Comment;
import com.aliang.shopping.security.PreventRepeatSubmit;
import com.aliang.shopping.security.auth.UserHolder;
import com.aliang.shopping.service.CommentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/comment")
@Api
@AllArgsConstructor
public class CommentController {

    private final CommentService commentService;
    private final CommentConverter commentConverter;
    private final OssConfig ossConfig;

    @PostMapping("/putComment/{ordersId}")
    @ApiOperation("发布评论")
    @PreventRepeatSubmit
    @OperateLog(title = "发布评论", type = OperateType.INSERT)
    public Result<String> putComment(@PathVariable("ordersId") Long ordersId, @RequestBody CommentInsertDTO inertDTO) {
        // 检查数据
        if (BeanUtil.hasNullField(inertDTO)) {
            throw new DataException(ResultCodeEnum.DATA_LACK);
        }
        //获取登录用户Id
        Long userId = UserHolder.getUserId();
        //没登录
        if (BeanUtil.isEmpty(userId)) {
            throw new DataException(ResultCodeEnum.USER_NOT_LOGIN);
        }
        // 转换数据
        Comment comment = this.commentConverter.toPoByInsertDTO(inertDTO, ossConfig.getUrl());
        // 设置用户Id和订单id
        comment.setUserId(userId);
        comment.setOrdersId(ordersId);
        //保存数据
        boolean save = this.commentService.save(comment);
        return save ? Result.ok(ResultMsgContact.COMMENT_PUSH_SUCCESS)
                : Result.fail("").message(ResultMsgContact.COMMENT_PUSH_FAIL);
    }
}
